package com.bawei.module_mall.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_mall.databinding.ItemOrderBinding
import com.bawei.module_mall.model.Order
import com.bumptech.glide.Glide
import com.bawei.module_mall.R

class OrderListAdapter(
    private var orders: List<Order>,
    private val onAction1Click: (Order) -> Unit,
    private val onAction2Click: (Order) -> Unit
) : RecyclerView.Adapter<OrderListAdapter.OrderViewHolder>() {

    class OrderViewHolder(
        private val binding: ItemOrderBinding,
        private val onAction1Click: (Order) -> Unit,
        private val onAction2Click: (Order) -> Unit
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(order: Order) {
            binding.order = order
            binding.executePendingBindings()

            // 加载图片
            val imageView = binding.ivProductImage
            if (!order.productImageUrl.isNullOrEmpty()) {
                Glide.with(imageView.context)
                    .load(order.productImageUrl)
                    .placeholder(R.drawable.bg_product_placeholder)
                    .error(R.drawable.bg_product_placeholder)
                    .into(imageView)
            } else {
                imageView.setImageResource(R.drawable.bg_product_placeholder)
            }

            binding.btnAction1.setOnClickListener {
                onAction1Click(order)
            }

            binding.btnAction2.setOnClickListener {
                onAction2Click(order)
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OrderViewHolder {
        val binding = ItemOrderBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return OrderViewHolder(binding, onAction1Click, onAction2Click)
    }

    override fun onBindViewHolder(holder: OrderViewHolder, position: Int) {
        holder.bind(orders[position])
    }

    override fun getItemCount(): Int = orders.size

    fun updateOrders(newOrders: List<Order>) {
        orders = newOrders
        notifyDataSetChanged()
    }
} 